(function() {

	var UserCon = require("../../core/user/_con");
	var db = require("../../core/db/index");
	var config = require("../../core/_include/config");
	var ResponObj = require("../_include/responObj");
	var helper = require("../../core/_include/helper");
	var role = require("./role");
	var http = require('http');
	// var ccap = require('uns-ccap');
	// var captcha = ccap();
	var ccapCache = {};
	var phoneCode = require("./phone_code");
	var imageCode = require("../../core/_include/imgcode");

	module.exports = {
		prefix: "/user",
		get: {
			//获取登录者的信息
			"/": function() {
				var query = this.request.query;
				if (query.openid) { //微信OPENID登录
					try {
						var user_loginning = role.getUser(this);
						user_loginning.setWeiXinUnionIDByOpenId(role.get_WX_V2_instance(this), query.openid);
					} catch (e) {
						console.error("SET WEIXIN LOGINER")
						console.error(e)
					}
					var user = UserCon.find_by_weixin_openid(role.get_WX_V2_instance(this), query.openid);
					//记录到登录Cookie中
					role.loginUser(this, user);
				} else {
					var user = role.getUser(this);
				}
				this.body = ResponObj("json", user);
			},
			//.query.method:"byname"||"byid"
			"/adminScan/:id_or_name": function() {
				//get:this.request.query
				//post:this.request.body
				//params:this.params
				var method = this.request.query.method;
				var id_or_name = this.params.id_or_name;
				if (method == "byname") {
					id_or_name = id_or_name.toLowerCase();
					var user = db.find_one(config.dbname.user, {
						info: {
							name: id_or_name
						}
					});
				} else {
					user = db.find_by_id(config.dbname.user, id_or_name);
				}
				if (user) {
					this.body = ResponObj("json", user);
					//TODO:过滤相应的字段
				} else {
					this.body = ResponObj("error", "找不到指定的用户")
				}
			},
			//用户退出登录
			"/loginout": function() {
				try {
					var user = role.getUser(this);
					//删除loginHash中同用户名的信息
					db.remove_list(config.dbname.loginHash, {
						user_id: user._id
					});
					//清空Cookie
					this.cookies.set("loginSession", "");
					this.body = ResponObj("json", "用户下线成功");
				} catch (errorMsg) {
					this.body = ResponObj("error", errorMsg);
				}
			},
			//获取用户登录的验证码
			"/loginCode": function() {
				var ary = captcha.get();
				var text = ary[0].toLowerCase();
				var buffer = ary[1];

				var hash = (+new Date) + Math.random().toString(16).substr(2);
				this.cookies.set("loginCode", hash);

				ccapCache[hash] = text;
				setTimeout(function() {
					delete ccapCache[hash];
				}, config.userCcapTimeOut);

				this.body = buffer;
			},
			//获取用户注册的短信验证码
			"/registerCode": function() {
				var self = this;
				var query = self.request.query;
				var mobile_phone = query.mobile_phone;
				// console.log("mobile_phone:", mobile_phone);
				if (!mobile_phone) {
					throwCusError("参数错误");
				}
				if (!helper.phone(mobile_phone)) {
					throwCusError("手机号码格式错误")
				}
				phoneCode.send("用户注册", mobile_phone);
				this.body = ResponObj("string", "验证码发送成功");
			},
			"/getImageCode": function() {
				var image_code_id = this.cookies.get("image_code_id");
				if (!image_code_id) {
					image_code_id = (Math.random() + "" + (+new Date)).substr(2);
					this.cookies.set("image_code_id", image_code_id);
				}
				var image_buff = imageCode.getImageCodeBuff(image_code_id);
				this.response.set("Content-Type", "image/png");
				this.body = image_buff;
			},
			"/registerCodeWithImageCode/:image_code": function() {
				var image_code = this.params.image_code;
				var query = this.request.query;
				var mobile_phone = query.mobile_phone;
				// console.log("mobile_phone:", mobile_phone);
				var image_code_id = this.cookies.get("image_code_id");
				if (!image_code_id) {
					throwCusError("未请求图形验证码");
				}
				if (!imageCode.checkImageCode(image_code_id, image_code)) {
					throwCusError("图形验证码输入有误");
				}
				//清除图形验证码缓存
				imageCode.CGImageCode(image_code_id);

				if (!mobile_phone) {
					throwCusError("未输入手机号码");
				}
				if (!helper.phone(mobile_phone)) {
					throwCusError("手机号码格式错误")
				}
				phoneCode.send("用户注册", mobile_phone);
				this.body = ResponObj("string", "验证码发送成功");
			},
			"/registerCheckedMobilePhone/:mobile_phone": function() {
				var mobile_phone = this.params.mobile_phone;
				if (!helper.phone(mobile_phone)) {
					throwCusError("手机号码格式不正确");
				}
				if (db.find_one(config.dbname.user, {
						info: {
							mobile_phone: mobile_phone
						}
					})) {
					throwCusError("手机号码已被使用")
				}
				this.body = ResponObj("json", "手机号码可用");
			},
			"/registerCheckedEmail/:email": function() {
				var email = this.params.email;
				if (!helper.isEmail(email)) {
					throwCusError("邮箱格式不正确");
				}
				if (db.find_one(config.dbname.user, {
						info: {
							email: email
						}
					})) {
					throwCusError("邮箱已被使用")
				}
				this.body = ResponObj("json", "邮箱可用");
			},
			// 获取用户推荐注册链
			"/getRecommenderLink": function() {
				var user = role.getUser(this);
				this.body = ResponObj("json", user.getRecommenderLink());
			}
		},
		post: {
			"/register": function() {
				var user_info = this.request.body;
				console.log(user_info)
				try {
					var bus = role.getBusInfo(this);
					user_info.register_bus_id = bus._id;
				} catch (e) {
					console.error(e)
				}
				//TODO:先验证验证码

				//用户名不分大小写
				if (!(user_info.password && user_info.confirm_password)) {
					console.log("password")

					throwCusError("表单不完整")
				} else if (user_info.password !== user_info.confirm_password) {
					console.log("confirm_password")
					throwCusError("两次密码输入不匹配")
				} else if (user_info.register_entryway !== "inside") {
					console.log("register_entryway")
					if (!user_info.phone_code && user_info.type !== 2) {
						throwCusError("验证码不可为空");
					} else if (user_info.phone_code !== phoneCode.get(user_info.mobile_phone) && user_info.type !== 2) {
						console.log(user_info.phone_code, phoneCode.get(user_info.mobile_phone))
						throwCusError("验证码错误")
					} else {
						var new_user = new UserCon(user_info);
						this.body = ResponObj("json", new_user);
					}
				} else {
					var new_user = new UserCon(user_info);
					this.body = ResponObj("json", new_user);
				}
			},
			//用户登录
			//.body:user_info
			"/login": function() {
				var query = this.request.query;
				if (query.from_bus) { //使用已经登录的商家身份进行登录
					var bus = role.getBus(this);
					var user = bus.asUser();
				} else {
					var form_data = this.request.body;
					//检查验证码
					// role.checkCode(this,"loginCode");

					//检查登录信息
					var user = UserCon.login(form_data);
				}
				role.loginUser(this, user, query);
				this.body = ResponObj("json", user);
			},
			//修改管理员信息附加
			"/update": function() {

			}
		},
		put: {
			//修改用户基础信息
			"/info": function() {
				var user = role.getUser(this);
				var user_info = this.request.body;
				user.setInfo(user_info);
				this.body = ResponObj("json", user);
			},
			"/password": function() {
				var user = role.getUser(this);
				var new_password = this.request.body.new_password;
				var old_password = this.request.body.old_password;
				user.setPassword(old_password, new_password);
				this.body = ResponObj("json", user);
			},
			"/bind_weixin_account_by_open_id": function() {
				var user = role.getUser(this);
				var body = this.request.body;
				var openid = body.openid;
				if (!openid) {
					throwCusError("参数错误");
				}
				user.setWeiXinUnionIDByOpenId(role.get_WX_V2_instance(this), openid);
				this.body = ResponObj("json", user);
			}
		}
	}

}());